import CommonEditor from '@/components/CommonEditor';
import MyCard from '@/components/MyCard';
import { uploadFileUsingPost } from '@/services/backend/fileController';
import { addPostUsingPost } from '@/services/backend/postController';
import { CloseCircleFilled, PictureOutlined } from '@ant-design/icons';
import { Button, Flex, Image, Input, message, Space, Upload, UploadProps } from 'antd';
import { useState } from 'react';

interface Props {
  callback: () => void;
}

const PostCard: React.FC<Props> = (props) => {
  const { callback } = props;
  const [postValue, setPostValue] = useState<string>('');
  const [titleValue, setTitleValue] = useState<string>('');
  const [imgFileInfoList, setImgFileInfoList] = useState<string[]>([]);

  /**
   * 上传图片的props
   */
  const imgProps: UploadProps = {
    beforeUpload: (file) => {
      //最多上传5张图片
      if (imgFileInfoList.length >= 5) {
        message.warning(`${file.name} 上传失败,最多上传5张图片`);
        return false;
      }
      //只允许img上传
      const isIMG = file.type === 'image/png' || file.type === 'image/jpeg';
      if (!isIMG) {
        message.error(`${file.name} is not a img file`);
      }
      return isIMG || Upload.LIST_IGNORE;
    },
    customRequest: async (options) => {
      const { file } = options;
      //上传图片
      try {
        const res = await uploadFileUsingPost({ biz: 'post_img' }, {}, file as File);
        //存储图片的url至list
        if (res.code === 0 && res.data) {
          if (imgFileInfoList) {
            setImgFileInfoList([...imgFileInfoList, res.data]);
          } else {
            setImgFileInfoList([res.data]);
          }
        }
        console.log(imgFileInfoList);
      } catch (e: any) {
        message.error(e.message);
      }
    },
    showUploadList: false,
  };

  /**
   * 处理移除img从List中
   */
  const handleRemoveImg = (info: string) => {
    console.log('remove=>', info);
    const updatedList = imgFileInfoList.filter((item) => item !== info);
    setImgFileInfoList(updatedList);
  };

  /**
   * 表单提交
   */
  const handleSubmit = async () => {
    try {
      const res = await addPostUsingPost({
        content: postValue,
        title: titleValue,
        pictures: imgFileInfoList,
      });
      if (res.code === 0) {
        message.success('发布成功');
        //删除输入框的文字与图片
        setPostValue('');
        setTitleValue('');
        setImgFileInfoList([]);
        //刷新评论
        callback();
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  return (
    <div id={'post'}>
      <div id={'post-inner'} className={'flex'}>
        <div id={'post-inner-content'} className={'flex-1'}>
          <MyCard title={'🚀发布帖子'}>
            <Flex gap={16} vertical={true}>
              <div className={'bg-gray-100 pb-1 rounded-lg'}>
                <div>
                  <Input
                    maxLength={80}
                    placeholder={'请输入标题~'}
                    value={titleValue}
                    onChange={(e) => setTitleValue(e.target.value)}
                    spellCheck={false}
                    variant={'borderless'}
                  />
                </div>
              </div>
              <div className={'bg-gray-100 pb-1 rounded-lg'}>
                <div>
                  <Input.TextArea
                    rows={3}
                    maxLength={8000}
                    placeholder={'请输入内容~'}
                    value={postValue}
                    onChange={(e) => setPostValue(e.target.value)}
                    spellCheck={false}
                    variant={'borderless'}
                    style={{ resize: 'none' }}
                  />
                </div>
                <div className={'flex flex-wrap gap-2 py-1 px-2'}>
                  {imgFileInfoList.map((imgFileInfo: string) => {
                    return (
                      <div key={1} className={'relative'}>
                        <span
                          className={'cursor-pointer hover:opacity-80'}
                          style={{
                            position: 'absolute',
                            top: '-6px',
                            right: '-6px',
                            zIndex: '50',
                          }}
                          onClick={() => handleRemoveImg(imgFileInfo)}
                        >
                          <CloseCircleFilled />
                        </span>
                        <Image className={'z-0'} width={80} src={imgFileInfo} />
                      </div>
                    );
                  })}
                </div>
              </div>
              <div className={'flex justify-between items-center'}>
                <Space direction={'horizontal'} align={'baseline'} size={'large'}>
                  <a>
                    <CommonEditor callback={(val) => setPostValue(postValue + val)} />
                  </a>
                  <Upload {...imgProps}>
                    <a>
                      <Space size={4}>
                        <PictureOutlined />
                        <span>图片</span>
                      </Space>
                    </a>
                  </Upload>
                </Space>
                <div>
                  <Button variant={'solid'} type={'primary'} shape={'round'} onClick={handleSubmit}>
                    发布
                  </Button>
                </div>
              </div>
            </Flex>
          </MyCard>
        </div>
      </div>
    </div>
  );
};

export default PostCard;
